package org.example;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.io.File;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;


@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
@Fork(1)
@Warmup(iterations = 3)
@Measurement(iterations = 10)
public class JMHMain {

    private static final String LINE_TXT = " - c++/go/cangjie 测试文本写入文件的速度/性能，需要高频写入日志的场景对写文件性能关注会比较高 - 2024 ++++ c++/go/cangjie 测试文本写入文件的速度/性能，需要高频写入日志的场景对写文件性能关注会比较高 - 2024";

    private long res;

    @Benchmark
    public void testStringWriteToFile() {
        res = stringWriteToFile();
    }

    @TearDown(Level.Iteration)
    public void showRes() {
        System.out.printf("文件写入完毕,文件总大小：%d\t耗时：", res);
    }

    public long stringWriteToFile() {
        String filePath = "D:/写文件/log_java_with_buffer.txt";
        long rows = 1000000;
        File file = new File(filePath);
        try (PrintWriter printWriter = new PrintWriter(file)) {
            for (long i = 1; i <= rows; i++) {
                printWriter.write(i + LINE_TXT + "\n");
            }
            printWriter.flush();
            return file.length();
        } catch (Exception e) {
            System.out.printf("创建文件出错：%s\n", e);
        }
        return 0;
    }

    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(JMHMain.class.getSimpleName())
                .build();
        new Runner(opt).run();
    }
}